package order

import (
	"context"
	

	"oil-station-backend/internal/svc"
	"oil-station-backend/internal/types"
	"oil-station-backend/internal/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetOrderListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderListLogic {
	return &GetOrderListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderListLogic) GetOrderList(req *types.OrderListReq) (resp *types.OrderListResp, err error) {
	// 从上下文中获取用户ID和角色
	userId, role, err := l.getUserInfoFromContext()
	if err != nil {
		return nil, err
	}

	// 判断是否是管理员
	isAdmin := role == "admin"
	
	// 使用改进后的FindList方法，直接在数据库层面过滤用户订单
	dbOrders, total, err := l.svcCtx.OrderModel.FindList(req.Status, userId, isAdmin, req.Page, req.Size)
	if err != nil {
		return nil, err
	}

	// 转换为API响应格式
	var orders []types.Order
	for _, order := range dbOrders {
		var completeTime string
		if order.CompleteTime != nil {
			completeTime = order.CompleteTime.Format("2006-01-02 15:04:05")
		}

		var actualVolume, actualAmount float64
		if order.ActualVolume != nil {
			actualVolume = *order.ActualVolume
		}
		if order.ActualAmount != nil {
			actualAmount = *order.ActualAmount
		}

		orders = append(orders, types.Order{
			Id:            order.Id,
			OrderNo:       order.OrderNo,
			UserId:        order.UserId,
			UserName:      order.UserName,
			FuelType:      order.FuelType,
			FuelPrice:     order.FuelPrice,
			Volume:        order.Volume,
			PrepaidAmount: order.PrepaidAmount,
			ActualVolume:  actualVolume,
			ActualAmount:  actualAmount,
			Status:        order.Status,
			CreateTime:    order.CreateTime.Format("2006-01-02 15:04:05"),
			UpdateTime:    order.UpdateTime.Format("2006-01-02 15:04:05"),
			CompleteTime:  completeTime,
		})
	}

	return &types.OrderListResp{
		List:  orders,
		Total: total,
	}, nil
}

func (l *GetOrderListLogic) getUserInfoFromContext() (int64, string, error) {
	// 使用通用工具函数获取用户信息
	return utils.GetUserInfoFromContext(l.ctx)
}